//
//  Message.m
//  Gabber
//
//  Created by 惠国 陆 on 11-10-10.
//  Copyright (c) 2011年 恒生聚源. All rights reserved.
//

#import "Message.h"


@implementation Message

@dynamic streamBareJidStr;
@dynamic jidStr;
@dynamic content;
@dynamic outbound;
@dynamic read;
@dynamic timestamp;

+ (id)insertInManagedObjectContext:(NSManagedObjectContext *)moc
                       withMessage:(XMPPMessage *)message
                  streamBareJidStr:(NSString *)streamBareJidStr
{

	if (!message.isChatMessageWithBody)
	{
		DDLogWarn(@"%@: %@ - Invalid chat message: %@", THIS_FILE, THIS_METHOD, message);
		return nil;
	}
	
	Message * newMessage;
	newMessage = [NSEntityDescription insertNewObjectForEntityForName:@"Message"
                                               inManagedObjectContext:moc];
    
	
	[newMessage updateWithMessage:message streamBareJidStr:streamBareJidStr];
	
	return newMessage;    
    
}

- (void)updateWithMessage:(XMPPMessage *)message streamBareJidStr:(NSString *)streamBareJidStr
{
    
	
	if (message.isChatMessageWithBody)
	{
        self.streamBareJidStr = streamBareJidStr;
        self.content = [[message elementForName:@"body"] stringValue];
        self.timestamp = [NSDate date];
        
        if (message.from) {
            self.outbound=[NSNumber numberWithBool:NO];
            self.read=[NSNumber numberWithBool:NO];
            self.jidStr = [message.from bare];            

        }else {
            self.outbound=[NSNumber numberWithBool:YES];
            self.read=[NSNumber numberWithBool:YES];
            self.jidStr = [message.to bare];
        }        
	}else
    {
		DDLogWarn(@"%@: %@ - Invalid chat message: %@", THIS_FILE, THIS_METHOD, message);
		return;        
    }
	
    
    
}


- (BOOL)isOutbound
{
    return [[self outbound] boolValue];
}

- (void)setIsOutbound:(BOOL)flag
{
    [self setOutbound:[NSNumber numberWithBool:flag]];
}


- (BOOL)hasBeenRead
{
    return [[self read] boolValue];
}

- (void)setHasBeenRead:(BOOL)flag
{
	if (flag != [self hasBeenRead])
	{
		
		[self setRead:[NSNumber numberWithBool:flag]];
        
	}
}

- (NSComparisonResult) timestampCompare:(Message *)msg
{
    return [msg.timestamp compare: self.timestamp];
}


@end
